//
//  HomeViewController.m
//  Commerce
//
//  Created by xiaofeifei on 15/1/30.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "HomeViewController.h"
#import "DDMenuController.h"
#import "HomeDetailViewController.h"
#import "OwnerdetailViewController.h"
#import "AreaViewController.h"
#import "HomeCell.h"
#import "OwnerCell.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>

#import "SpecialLineViewController.h"
#import "LoginViewController.h"
#import "SendMsgViewController.h"
#import "ShortListViewController.h"

@interface HomeViewController ()<BMKLocationServiceDelegate>{
    NSMutableArray *_dataArray;
    BMKLocationService* _locService;
    UIView *_detailBgView;
    NSArray *_specificationArray;
    NSArray *_typeArray;
    NSDictionary *_startingDic;
    NSDictionary *_destinationDic;
    
    BOOL _hasLoad;
}

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    if (_isOwner) {
//        self.navStr = @"今日车源";
//    }else{
//        self.navStr = @"即时货源";
//    }
    
    _dataArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    _specificationArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"SpecificationData"];
    _typeArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"TypeData"];
    if (_specificationArray.count == 0) {
        [self getSpecificationData];
    }
    if (_typeArray.count == 0) {
        [self getTypeData];
    }
    
    _specificationTextField.inputAccessoryView = _doneToolBar;
    _specificationTextField.inputView = _dataPicker;
    _typeTextField.inputAccessoryView = _doneToolBar;
    _typeTextField.inputView = _typeDataPicker;
    
    //精确查找
    _detailBgView = [[UIView alloc] initWithFrame:self.view.bounds];
    [_detailBgView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_detailBgView];
    UIControl *bgView = [[UIControl alloc] initWithFrame:_detailBgView.bounds];
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setAlpha:0.5];
    [bgView addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [_detailBgView addSubview:bgView];
    _searchView.layer.masksToBounds = YES;
    _searchView.layer.cornerRadius = 5.0;
    [_searchView setFrame:CGRectMake(20, 100, 280, 260)];
    [_detailBgView addSubview:_searchView];
    [self cancel];

    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 50, 44)];
    [leftBtn setImage:[UIImage imageNamed:@"left.png"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(showLeft:) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:leftBtn];
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 50, 20, 50, 44)];
    [rightBtn setImage:[UIImage imageNamed:@"right.png"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(showRight:) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:rightBtn];
    
    [self refreshData];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [self startLocation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getRefresh:) name:@"HomeList" object:nil];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (!_hasLoad) {
        [self configUI];
        [self.tableView setFrame:CGRectMake(0, _topView.frame.size.height +_topView.frame.origin.y, self.tableView.frame.size.width,self.view.frame.size.height - (_topView.frame.size.height +_topView.frame.origin.y)-40)];
        _hasLoad = YES;
    }
}

- (void)configUI{
    UIView *buttomview = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-40, self.view.frame.size.width, 40)];
    [buttomview setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:buttomview];
    
    UIImageView *bgImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttom_bg.png"]];
    bgImg.frame = buttomview.bounds;
    [buttomview addSubview:bgImg];
    
    UIButton *fahuoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    fahuoBtn.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [fahuoBtn setTitle:@"发货" forState:UIControlStateNormal];
//    [fahuoBtn setBackgroundImage:[UIImage imageNamed:@"fahuo"] forState:UIControlStateNormal];
    [fahuoBtn addTarget:self action:@selector(gotoFaHuo) forControlEvents:UIControlEventTouchUpInside];
    [fahuoBtn setFrame:CGRectMake(30, 0, 50, 40)];
    [buttomview addSubview:fahuoBtn];
    
    UIButton *zhaocheBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    zhaocheBtn.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [zhaocheBtn setTitle:@"找短驳" forState:UIControlStateNormal];
//    [zhaocheBtn setBackgroundImage:[UIImage imageNamed:@"zhaoche"] forState:UIControlStateNormal];
    [zhaocheBtn addTarget:self action:@selector(gotoZhaoChe) forControlEvents:UIControlEventTouchUpInside];
    [zhaocheBtn setFrame:CGRectMake(30+107, 0, 50, 40)];
    [buttomview addSubview:zhaocheBtn];
    
    UIButton *zhaozhuanxianBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    zhaozhuanxianBtn.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [zhaozhuanxianBtn setTitle:@"找专线" forState:UIControlStateNormal];
//    [zhaozhuanxianBtn setBackgroundImage:[UIImage imageNamed:@"zhaozhuanxian"] forState:UIControlStateNormal];
    [zhaozhuanxianBtn addTarget:self action:@selector(gotoZhaoZhuanXian) forControlEvents:UIControlEventTouchUpInside];
    [zhaozhuanxianBtn setFrame:CGRectMake(25+106*2, 0, 50, 40)];
    [buttomview addSubview:zhaozhuanxianBtn];
    
    UIImageView *lineImg1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttom_bg01"]];
    lineImg1.frame = CGRectMake(106, 0, 1, 40);
    [buttomview addSubview:lineImg1];
    
    UIImageView *lineImg2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttom_bg01"]];
    lineImg2.frame = CGRectMake(106*2, 0, 1, 40);
    [buttomview addSubview:lineImg2];
    
}

- (void)showLeft:(id)sender{
    DDMenuController *menuController = (DDMenuController *)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    [menuController showLeftController:YES];
}

- (void)showRight:(id)sender{
    DDMenuController *menuController = (DDMenuController *)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    [menuController showRightController:YES];
}

#pragma mark -IBAction
- (void)gotoFaHuo{

    UIViewController *vc = nil;
    if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
        [SVProgressHUD showInfoWithStatus:@"请先登录"];
        vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
    }else{
        vc = [[SendMsgViewController alloc] initWithNibName:nil bundle:nil];
        [(BasicViewController *)vc setNavStr:@"发布货源"];
    }
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoZhaoChe{
//    
//    _isOwner = YES;
//    [self refreshData];
//    self.navLabel.text = @"今日车源";
    
    ShortListViewController *vc = [[ShortListViewController alloc] initWithNibName:nil bundle:nil];
    vc.navStr = @"短驳查询";
    UINavigationController *navController = (UINavigationController*)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    [navController pushViewController:vc animated:YES];
}

- (void)gotoZhaoZhuanXian{
   SpecialLineViewController *vc = [[SpecialLineViewController alloc] initWithNibName:nil bundle:nil];
    vc.navStr = @"专线查找";
    UINavigationController *navController = (UINavigationController*)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    [navController pushViewController:vc animated:YES];
}

- (void)cancel{
    _specificationTextField.text = @"";
    _typeTextField.text = @"";
    _startingTextField.text =@"";
    _destinationTextField.text =@"";
    [_detailBgView setHidden:YES];
}

- (IBAction)showDetailView:(id)sender{
    [_detailBgView setHidden:NO];
}


- (IBAction)clickSearch:(id)sender{
    [self refreshData];
}

- (IBAction)doneSelect:(id)sender {
    if ([_specificationTextField isFirstResponder]) {
        _specificationTextField.text = [_specificationArray objectAtIndex:[_dataPicker selectedRowInComponent:0]][@"Text"];
        [_specificationTextField resignFirstResponder];
    }
    if ([_typeTextField isFirstResponder]) {
        _typeTextField.text = [_typeArray objectAtIndex:[_typeDataPicker selectedRowInComponent:0]][@"Text"];
        [_typeTextField resignFirstResponder];
    }
}
//- (void)getDate{
//    NSDate *date = [NSDate date];
//    NSDateFormatter *df = [[NSDateFormatter alloc] init];
//    [df setDateFormat:@"dd-MM-yyyy"];
//    _dateLabel.text = [df stringFromDate:date];
//}

- (IBAction)gotoStartingView:(id)sender{
    AreaViewController *vc = [[AreaViewController alloc] initWithNibName:nil bundle:nil];
    vc.typeNum = 1;
    vc.delegate =self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)gotoDestinationView:(id)sender{
    AreaViewController *vc = [[AreaViewController alloc] initWithNibName:nil bundle:nil];
    vc.typeNum = 2;
    vc.delegate =self;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -AreaDelegate
- (void)showAreaData:(NSInteger)TypeNum andArea:(NSDictionary *)areaDic andAreaName:(NSString *)areaName{
    if (TypeNum == 1) {
        _startingDic = areaDic;
        _startingTextField.text = areaName;
    }else if (TypeNum == 2){
        _destinationDic = areaDic;
        _destinationTextField.text = areaName;
    }
}

#pragma mark -startLocation
- (void)startLocation{
    //启动LocationService
    [_locService startUserLocationService];
}

#pragma mark -
#pragma mark loction
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_locService stopUserLocationService];
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    [[GlobalData sharedGlobalData] setUselocation:userLocation.location.coordinate];
    [[GlobalData sharedGlobalData] setBUserLocation:userLocation];
    
    [self getWeather];
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

#pragma mark -noti
- (void)getRefresh:(NSNotification *)noti{
    _isOwner = [[noti object][@"menu"] boolValue];
    self.navLabel.text = [noti object][@"name"];
    [self refreshData];
}

#pragma mark -请求数据
- (void)getDataList
{
    if (_isOwner) {
        [self getOwnerList];
    }else{
        [self getShipperList];
    }
}

- (void)getShipperList{//货源列表
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    
    //传入的参数
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [parameters addEntriesFromDictionary:@{@"page_index":[NSString stringWithFormat:@"%d",self.page],
                                           @"page_size":[NSString stringWithFormat:@"%d",self.pageLimit],
                                           @"car_type":[_typeTextField.text isEqual:[NSNull null]] ? @"":_typeTextField.text,
                                           @"car_spec":[_specificationTextField.text isEqual:[NSNull null]] ? @"":_specificationTextField.text,
                                           @"start_address":[_startingDic[@"AreaID"] length] == 0 ? @"":_startingDic[@"AreaID"],
                                           @"end_address":[_destinationDic[@"AreaID"] length] == 0 ? @"":_destinationDic[@"AreaID"]
                                           }];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@pro/list",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  [SVProgressHUD dismiss];
                                  id responseObject = result;
                                  if ([responseObject isKindOfClass:[NSArray class]]) {
                                      if ([(NSArray *)responseObject count] < self.pageLimit) {
                                          self.canLoadMore = NO;
                                      }else{
                                          self.canLoadMore = YES;
                                      }
                                      if (self.page == 1) {
                                          [self.tableView setContentOffset:CGPointZero animated:NO];
                                          [_dataArray removeAllObjects];
                                          [_dataArray addObjectsFromArray:responseObject];
                                          [self addItemsOnTop];
                                      }else{
                                          [_dataArray addObjectsFromArray:responseObject];
                                          [self addItemsOnBottom];
                                      }
                                  }else{
                                      [self loadMoreCompleted];
                                  }
                                  [self cancel];
                                  
                              }];
}

- (void)getOwnerList{//车源列表
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];

    //传入的参数
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [parameters addEntriesFromDictionary:@{@"page_index":[NSString stringWithFormat:@"%d",self.page],
                                           @"page_size":[NSString stringWithFormat:@"%d",self.pageLimit],
                                           @"car_type":[_typeTextField.text isEqual:[NSNull null]] ? @"":_typeTextField.text,
                                           @"car_spec":[_specificationTextField.text isEqual:[NSNull null]] ? @"":_specificationTextField.text,
                                           @"start_address":[_startingDic[@"AreaID"] length] == 0 ? @"":_startingDic[@"AreaID"],
                                           @"end_address":[_destinationDic[@"AreaID"] length] == 0 ? @"":_destinationDic[@"AreaID"]
                                           }];
    
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@car/list",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  if ([responseObject isKindOfClass:[NSArray class]]) {
                                      if ([(NSArray *)responseObject count] < self.pageLimit) {
                                          self.canLoadMore = NO;
                                      }else{
                                          self.canLoadMore = YES;
                                      }
                                      if (self.page == 1) {
                                          [self.tableView setContentOffset:CGPointZero animated:NO];
                                          [_dataArray removeAllObjects];
                                          [_dataArray addObjectsFromArray:responseObject];
                                          [self addItemsOnTop];
                                      }else{
                                          [_dataArray addObjectsFromArray:responseObject];
                                          [self addItemsOnBottom];
                                      }
                                  }else{
                                      [self loadMoreCompleted];
                                  }
                                  [_detailBgView setHidden:YES];
                              }];

}

- (void)getWeather{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"http://api.map.baidu.com/telematics/v3/weather?location=%f,%f&output=json&ak=Lu04j3u68l1okkkh7WEgGAmz&coord_type=bd09ll&mcode=com.zhangjf.logistics",[[GlobalData sharedGlobalData] uselocation].longitude,[[GlobalData sharedGlobalData] uselocation].latitude]
                                    params:nil
                               requestMode:DGHTTPMethodGET
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSString *city = responseObject[@"results"][0][@"currentCity"];
                                  NSString *weather = responseObject[@"results"][0][@"weather_data"][0][@"weather"];
                                  NSString *temperature = responseObject[@"results"][0][@"weather_data"][0][@"temperature"];
                                  _weatherLabel.text = [NSString stringWithFormat:@"%@ %@ %@",city,weather,temperature];
                                  _dateLabel.text = responseObject[@"date"];
                                  [SVProgressHUD dismiss];
                              }];
}

- (void)getSpecificationData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/carspec",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSLog(@"responseObject=%@",responseObject);
                                  
                                  NSMutableArray *temp = [[NSMutableArray alloc] init];
                                  [temp addObject:@{@"Code":@"0",@"CodeID":@"0",@"CodeType":@"0",@"Text":@"不限制"}];
                                  [temp addObjectsFromArray:responseObject];
                                  _specificationArray = temp;
                                  [[NSUserDefaults standardUserDefaults] setObject:_specificationArray forKey:@"SpecificationData"];
                                  [[NSUserDefaults standardUserDefaults] setObject:_specificationArray forKey:@"SpecificationData"];
                                  [SVProgressHUD dismiss];
                              }];
}

- (void)getTypeData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/cartype",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSLog(@"responseObject=%@",responseObject);
                                  NSMutableArray *temp = [[NSMutableArray alloc] init];
                                  [temp addObject:@{@"Code":@"0",@"CodeID":@"0",@"CodeType":@"0",@"Text":@"不限制"}];
                                  [temp addObjectsFromArray:responseObject];
                                  _typeArray = temp;
                                  [[NSUserDefaults standardUserDefaults] setObject:_typeArray forKey:@"TypeData"];
                                  
                                  [SVProgressHUD dismiss];
                              }];
}

#pragma mark -
#pragma mark picker methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if ([_specificationTextField isFirstResponder]) {
        return _specificationArray.count;
    }
    return _typeArray.count;
}

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSString *title;
    if ([_specificationTextField isFirstResponder]) {
        title = [_specificationArray objectAtIndex:row][@"Text"];
    }else{
        title = [_typeArray objectAtIndex:row][@"Text"];
    }
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
}

#pragma mark - Table View Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 66;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isOwner) {
        static NSString *CellIdentifier = @"OwnerCell";
        
        OwnerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"OwnerCell" owner:self options:nil];
            cell = (OwnerCell *)[array objectAtIndex:0];
        }
        [cell configUIWithData:_dataArray[indexPath.row]];
        
        return cell;
    }else{
        static NSString *CellIdentifier = @"Cell";
        
        HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"HomeCell" owner:self options:nil];
            cell = (HomeCell *)[array objectAtIndex:0];
        }
        [cell configUIWithData:_dataArray[indexPath.row]];
        
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_isOwner) {
        OwnerdetailViewController *vc = [[OwnerdetailViewController alloc] initWithNibName:nil bundle:nil];
        vc.carId =_dataArray[indexPath.row][@"CarID"];
        vc.navStr = _dataArray[indexPath.row][@"CarTypeName"];
        [(UINavigationController *)self.view.window.rootViewController pushViewController:vc animated:YES];
    }else{
        HomeDetailViewController *vc = [[HomeDetailViewController alloc] initWithNibName:nil bundle:nil];
        vc.goodsId =_dataArray[indexPath.row][@"GoodsID"];
        vc.navStr = _dataArray[indexPath.row][@"GoodsName"];
        [(UINavigationController *)self.view.window.rootViewController pushViewController:vc animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
